// pages/Order/SubmitOrder/SubmitOrder.js
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetStore , queryPetInfo , queryPetGoodsStock } from '../../../api/pet';
import { submitPetTravelOrder , payPetTravelOrder } from '../../../api/petOrder';
import { checkUserPasswordIsSet } from '../../../api/login';
import { queryUserWechatOpenId , getUserAccount , getUser } from '../../../api/user';
import { getChannel } from '../../../api/brand';
const regeneratorRuntime = require('../../../common/runtime');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    safaBtm: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom,
    goods: {},
    CustomBar: app.globalData.CustomBar,
    petId: '',
    petInfo: {},
    storeId: '',
    store: {},
    userName: "",
    phone: '',
    remarks: '',
    quantity: 1,
    autosize: {
      minHeight: '200rpx',
      maxHeight: '200rpx'
    },
    showPayType: false,
    balance: 0,
    channel: [], // 支付方式
    payType: '1',
    user: {},
    surplusStock: 0,
    unionid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.goods){
      var goods = JSON.parse(options.goods);
      console.log(goods,'goods');
      this.setData({
        goods: goods,
        storeId: goods.storeId.split(',')[0]
      })
      this._queryPetInfo();
      this._queryPetStore();
      this._getChannel();
      this._getUser();
      this._queryUserWechatUnionId();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this._getUserAccount();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 输入框
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    const name = event.target.dataset.name||event.currentTarget.dataset.name;
    console.log(name,'name')
    // this.setData({
    //     name: event.detail,
    // })
    var data = this.data;
    data[name] =  event.detail;
    this.setData(data);
  },
  // 选择宠物
  selPet(){
    let _this = this;
    wx.navigateTo({
      url: '/pages/Pet/PetList/PetList',
      events: {
        'selPetInfo': function(data){
          console.log(data);
          _this.setData({
            petId: data.data,
          })
          _this._queryPetInfo();
        }
      }
    })
  },
  // 选择门店
  selStore(){
    let _this = this;
    wx.setStorageSync('selNearByStore','1');
    wx.navigateTo({
      url: '/pages/Pet/NearByStore/NearByStore?storeIdList='+_this.data.goods.storeId,
      events: {
        'selStore': function(data){
          console.log(data,'mendian')
          _this.setData({
            storeId: data.data,
          })
          _this._queryPetStore();
        }
      }
    })
  },
  // 获取宠物门店
  _queryPetStore() {
    let _this = this;
    const { queryLongitude, queryLatitude } = _this.data;
    queryPetStore({size: 99, queryLongitude: queryLongitude, queryLatitude: queryLatitude,id: _this.data.storeId})
    .then(res => {
      if (res.success) {
        _this.setData({
          storeId: res.data.content.length > 0 ? res.data.content[0].id : '',
          store: res.data.content.length > 0 ? res.data.content[0] : {},
        })
        _this._queryPetGoodsStock();
      } else {
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询宠物信息
  _queryPetInfo(){
    let _this = this;
    queryPetInfo({id: _this.data.petId,userId: wx.getStorageSync('userId')})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            petInfo: res.data.content[0],
            petId: res.data.content[0].id,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 下单数量
  onQuantityChange(event){
    this.setData({
      quantity: event.detail,
    })
  },
  // 下单
  submitOrder(){
    let _this = this;
    const { userName , phone , storeId , petId , quantity , surplusStock } = _this.data;
    if(userName == ''){
      wx.showToast({
        title: '请输入主人姓名',
        icon: 'none',
      });
      return;
    }
    if(phone == ''){
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none',
      });
      return;
    }
    if(storeId == ''){
      wx.showToast({
        title: '请选择门店信息',
        icon: 'none',
      });
      return;
    }
    if(petId == ''){
      wx.showToast({
        title: '请选择宠物信息',
        icon: 'none',
      });
      return;
    }
    if(quantity > surplusStock){
      wx.showToast({
        title: '当前门店库存不足，请尝试更换其他门店报名',
        icon: 'none',
      });
      return;
    }
    _this.setData({
      showPayType: true
    })
  },
  // 下单
  _submitOrder(){
    let _this = this;
    const { userName , phone , storeId , petId , quantity , remarks } = _this.data;
    submitPetTravelOrder({phone: phone,userName: userName,petId: petId,storeId: storeId,quantity: quantity,remarks: remarks,goodsId: _this.data.goods.id})
    .then(res => {
      if(res.success){
        _this.pay({orderCode:res.data.orderCode,payType:_this.data.payType});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  pay({orderCode,payType,amount}){
    let _this = this;
    payPetTravelOrder({payType: payType,orderCode: orderCode,openId: _this.data.unionid,payPassword: payType == '1' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({orderCode: orderCode,payType: payType,wechatSign: res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({orderCode,payType,wechatSign}){
    let _this = this;
    if(_this.data.payType == 1){
      wx.navigateTo({
        url: `/pages/Order/SubscribeSuccess/SubscribeSuccess?type=1&orderCode=${orderCode}`,
      })
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          wx.navigateTo({
            url: `/pages/Order/SubscribeSuccess/SubscribeSuccess?type=1&orderCode=${orderCode}`,
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitOrder();
  },
  // 校验是否设置过支付密码
  _checkUserPasswordIsSet(){
    let _this = this;
    return new Promise((resolve,reject) => {
      checkUserPasswordIsSet({})
      .then(res => {
        if(res.success){
          resolve(true)
        }else{
          resolve(false)
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              unionid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取通道配置信息
  _getChannel(){
    let _this = this;
    getChannel({isOn: '1'})
    .then(res => {
      if(res.success){
        var list = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          if((item.channelName.indexOf('微信支付') != -1 || item.channelName.indexOf('余额支付') != -1) && item.isOn == '1'){
            list.push(item);
          }
        }
        console.log(list,'支付通道')
        _this.setData({
          channel: list,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(){
    let _this = this;
    getUserAccount({})
    .then(res => {
      if(res.success){
        _this.setData({
          balance : res.data.balance,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  onClose(){
    this.setData({showPayType: false})
  },
  // 切换支付方式
  selPayType(e){
    const item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      payType: item.payType,
    })
  },
  // 确认支付
  async popPay(){
    let _this = this;
    this.onClose();
    if(_this.data.payType == 1){
      if(_this.data.goods.price > _this.data.balance){
        wx.showToast({
          title: '当前余额不足，请更换其他支付方式.',
          icon: 'none'
        })
        return;
      }
      const isSetPayPassword = await _this._checkUserPasswordIsSet();
      if(!isSetPayPassword){
        if(_this.data.user.phone.length != 11){
          wx.showModal({
            title: '温馨提示',
            content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
            success: (modal) =>{
              if(modal.confirm){
                wx.navigateTo({
                  url: '/pages/Users/BindPhone/BindPhone',
                })
              }
            },
          })
          return;
        }
        wx.showModal({
          title: '温馨提示',
          content: '暂未设置交易密码，是否前往设置？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
              })
            }
          },
        })
        return;
      }
      const child = _this.selectComponent('.pay-passwordAuth');
      console.log(child,'child')
      child.clearPassword();
      child.openPayAuth();
    }else{
      _this._submitOrder();
    }
  },
  // 获取用户个人信息
  _getUser(){
    let _this = this;
    getUser({})
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品库存信息
  _queryPetGoodsStock(){
    let _this = this;
    queryPetGoodsStock({goodsId: _this.data.goods.id,storeId: _this.data.storeId})
    .then(res => {
      if(res.success){
        _this.setData({
          surplusStock: res.data.content.length > 0 ? res.data.content[0].surplusStock : 0,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})